//
//  UIViewController+FQDStatusBar.m
//  FakeQDaily
//
//  Created by mewxiv on 8/20/16.
//  Copyright © 2016 Xensius. All rights reserved.
//

#import "UIViewController+FQDStatusBar.h"
#import <objc/runtime.h>

@implementation UIViewController (FQDStatusBar)


+ (void)load
{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        method_exchangeImplementations(class_getInstanceMethod(self, @selector(preferredStatusBarStyle)),
                                       class_getInstanceMethod(self, @selector(fqd_preferredStatusBarStyle)));
    });
}

- (FQDStatusBarStyle)fqd_statusBarStyle
{
    return [objc_getAssociatedObject(self, @selector(fqd_statusBarStyle)) integerValue];
}

- (void)setFqd_statusBarStyle:(FQDStatusBarStyle)fqd_statusBarStyle
{
    objc_setAssociatedObject(self, @selector(fqd_statusBarStyle), @(fqd_statusBarStyle), OBJC_ASSOCIATION_RETAIN_NONATOMIC);
    
    switch (fqd_statusBarStyle) {
        case FQDStatusBarStyleDarkTranslucent:
            // fall through
        case FQDStatusBarStyleLightTranslucent:
            self.fqd_statusBarView.hidden = YES;
            break;
            
        case FQDStatusBarStyleDarkOpaque:
            self.fqd_statusBarView.hidden = NO;
            self.fqd_statusBarView.backgroundColor = [UIColor whiteColor];
            break;
            
        case FQDStatusBarStyleLightOpaque:
            self.fqd_statusBarView.hidden = NO;
            self.fqd_statusBarView.backgroundColor = [UIColor blackColor];
            break;
    }
    [self setNeedsStatusBarAppearanceUpdate];
}

- (UIView *)fqd_statusBarView
{
    UIView *statusBarView = objc_getAssociatedObject(self, @selector(fqd_statusBarView));
    if (statusBarView == nil) {
        CGRect barFrame = [UIApplication sharedApplication].statusBarFrame;
        statusBarView = [[UIView alloc] initWithFrame:barFrame];
        statusBarView.backgroundColor = [UIColor whiteColor];
        statusBarView.hidden = YES;
        [self.view addSubview:statusBarView];
        objc_setAssociatedObject(self, @selector(fqd_statusBarView), statusBarView, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
    }
    return statusBarView;
}

- (UIStatusBarStyle)fqd_preferredStatusBarStyle
{
    UIStatusBarStyle barStyle;
    switch (self.fqd_statusBarStyle) {
        case FQDStatusBarStyleDarkOpaque:
            barStyle = UIStatusBarStyleDefault;
            break;
            
        case FQDStatusBarStyleLightOpaque:
            barStyle = UIStatusBarStyleLightContent;
            break;
            
        default:
            barStyle = (UIStatusBarStyle)self.fqd_statusBarStyle;
            break;
    }
    return barStyle;
}


@end
